package aclass.rocksea.com.database.db;

import android.content.Context;

import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.DataBaseConfig;
import com.litesuits.orm.db.assit.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mrw on 2017/7/5.
 *
 */

public class LiteOrmHelper {

    private static LiteOrm mLiteOrm;

    private static LiteOrmHelper mLiteOrmHelper;

    private LiteOrmHelper(Context context){
        createTable(context,"Note.db");
        createTable(context,"Message.db");
    }
    /**
     * 初始化数据库
     * */
    public static LiteOrmHelper initLiteOrm(Context context){
        if (mLiteOrmHelper==null){
            synchronized (LiteOrmHelper.class){
                mLiteOrmHelper = new LiteOrmHelper(context);
            }
        }
        return mLiteOrmHelper;
    }

    //创建表
    private static void createTable(Context context,String tableName){
        DataBaseConfig config = new DataBaseConfig(context);
        config.dbName = tableName;
        config.dbVersion = 1;
        config.debugged = true;
        mLiteOrm = LiteOrm.newCascadeInstance(config);
    }
    public <T> List<T> query(Class<T> cls){
        return mLiteOrm.query(cls);
    }
    public <T> void insert(T cls){
        mLiteOrm.insert(cls);
    }
    public <T> void detele(T cls){
        mLiteOrm.delete(cls);
    }

    /**
     * 插入所有记录
     * @param list
     */
    public static <T> void insertAll(List<T> list){
        mLiteOrm.insert(list);
    }

    /**
     * 查询所有
     * @param cla
     * @return
     */
    public static <T> ArrayList<T> getQueryAll(Class<T> cla){
        return mLiteOrm.query(cla);
    }

    /**
     * 查询  某字段 等于 Value的值
     * @param cla
     * @param field
     * @param value
     * @return
     */
    public static <T> ArrayList getQueryByWhere(Class<T> cla, String field, String [] value){
        return mLiteOrm.<T>query(new QueryBuilder(cla).where(field + "=?", value));
    }

    /**
     * 查询  某字段 等于 Value的值  可以指定从1-20，就是分页
     * @param cla
     * @param field
     * @param value
     * @param start
     * @param length
     * @return
     */
    public static <T> ArrayList getQueryByWhereLength(Class<T> cla, String field, String [] value, int start, int length){
        return mLiteOrm.<T>query(new QueryBuilder(cla).where(field + "=?", value).limit(start, length));
    }

}
